// 资产管理 API 服务
import type { 
  Asset, 
  AssetCategory, 
  PortfolioOverview, 
  PriceData, 
  HistoryPrice, 
  PerformanceData,
  ApiResponse,
  PaginatedResponse,
  AssetFormData,
  CategoryFormData,
  AssetFilters
} from '@/types/assets'
import type { RevenueTrendData, ExpenseTrendData } from '@/types/trend'
import { apiRequest, getUserAuthHeaders, API_CONFIG } from '@/config/api'

// 模拟延迟
const delay = (ms: number) => new Promise(resolve => setTimeout(resolve, ms))

class AssetService {
  // 1. 资产分类管理
  
  /**
   * 获取资产分类列表
   */
  async getCategories(): Promise<ApiResponse<AssetCategory[]>> {
    await delay(500)
    
    // TODO: 替换为真实API调用
    // return fetch('/api/assets/categories').then(res => res.json())
    
    return {
      code: 200,
      success: true,
      message: '获取成功',
      data: [
        { id: 1, name: '股票', icon: 'TrendingUp', color: 'bg-blue-500', total_value: 150000, count: 5 },
        { id: 2, name: '基金', icon: 'PieChart', color: 'bg-green-500', total_value: 80000, count: 3 },
        { id: 3, name: '加密货币', icon: 'DollarSign', color: 'bg-orange-500', total_value: 25000, count: 4 },
        { id: 4, name: '债券', icon: 'BarChart3', color: 'bg-purple-500', total_value: 60000, count: 2 },
        { id: 5, name: '房产', icon: 'TrendingUp', color: 'bg-indigo-500', total_value: 2000000, count: 1 },
        { id: 6, name: '贵金属', icon: 'DollarSign', color: 'bg-yellow-500', total_value: 30000, count: 2 },
        { id: 7, name: '期货', icon: 'Activity', color: 'bg-red-500', total_value: 45000, count: 3 },
        { id: 8, name: '外汇', icon: 'DollarSign', color: 'bg-teal-500', total_value: 15000, count: 2 }
      ]
    }
  }

  /**
   * 创建资产分类
   */
  async createCategory(data: CategoryFormData): Promise<ApiResponse<AssetCategory>> {
    await delay(500)
    
    // TODO: 替换为真实API调用
    // return fetch('/api/assets/categories', {
    //   method: 'POST',
    //   headers: { 'Content-Type': 'application/json' },
    //   body: JSON.stringify(data)
    // }).then(res => res.json())
    
    const newCategory: AssetCategory = {
      id: Date.now(),
      name: data.name,
      icon: data.icon,
      color: data.color,
      total_value: 0,
      count: 0
    }
    
    return {
      code: 200,
      success: true,
      message: '创建成功',
      data: newCategory
    }
  }

  /**
   * 更新资产分类
   */
  async updateCategory(id: number, data: CategoryFormData): Promise<ApiResponse<AssetCategory>> {
    await delay(500)
    
    // TODO: 替换为真实API调用
    // return fetch(`/api/assets/categories/${id}`, {
    //   method: 'PUT',
    //   headers: { 'Content-Type': 'application/json' },
    //   body: JSON.stringify(data)
    // }).then(res => res.json())
    
    const updatedCategory: AssetCategory = {
      id,
      name: data.name,
      icon: data.icon,
      color: data.color,
      total_value: 0,
      count: 0
    }
    
    return {
      code: 200,
      success: true,
      message: '更新成功',
      data: updatedCategory
    }
  }

  /**
   * 删除资产分类
   */
  async deleteCategory(_id: number): Promise<ApiResponse<null>> {
    await delay(500)
    
    // TODO: 替换为真实API调用
    // return fetch(`/api/assets/categories/${id}`, {
    //   method: 'DELETE'
    // }).then(res => res.json())
    
    return {
      code: 200,
      success: true,
      message: '删除成功',
      data: null
    }
  }

  // 2. 资产管理

  /**
   * 获取资产列表
   */
  async getAssets(_filters?: AssetFilters): Promise<ApiResponse<PaginatedResponse<Asset>>> {
    await delay(500)
    
    // TODO: 替换为真实API调用
    // const params = new URLSearchParams()
    // if (filters?.category_id) params.append('category_id', filters.category_id.toString())
    // if (filters?.search_term) params.append('search', filters.search_term)
    // return fetch(`/api/assets?${params}`).then(res => res.json())
    
    const mockAssets: Asset[] = [
      {
        id: 1, name: '苹果公司', symbol: 'AAPL', category_id: 1, category_name: '股票',
        quantity: 100, purchase_price: 150, current_price: 180, purchase_date: '2024-01-15',
        total_value: 18000, profit_loss: 3000, profit_loss_percentage: 20, notes: '科技股长期持有'
      },
      {
        id: 2, name: '特斯拉', symbol: 'TSLA', category_id: 1, category_name: '股票',
        quantity: 50, purchase_price: 200, current_price: 250, purchase_date: '2024-02-10',
        total_value: 12500, profit_loss: 2500, profit_loss_percentage: 25
      },
      {
        id: 3, name: '比特币', symbol: 'BTC', category_id: 3, category_name: '加密货币',
        quantity: 0.5, purchase_price: 40000, current_price: 45000, purchase_date: '2024-03-01',
        total_value: 22500, profit_loss: 2500, profit_loss_percentage: 12.5
      }
    ]
    
    return {
      code: 200,
      success: true,
      message: '获取成功',
      data: {
        items: mockAssets,
        total: mockAssets.length,
        page: 1,
        limit: 10
      }
    }
  }

  /**
   * 添加资产
   */
  async createAsset(data: AssetFormData): Promise<ApiResponse<Asset>> {
    await delay(500)
    
    // TODO: 替换为真实API调用
    // return fetch('/api/assets', {
    //   method: 'POST',
    //   headers: { 'Content-Type': 'application/json' },
    //   body: JSON.stringify(data)
    // }).then(res => res.json())
    
    const newAsset: Asset = {
      id: Date.now(),
      name: data.name,
      symbol: data.symbol,
      category_id: parseInt(data.category_id),
      category_name: '未知', // 需要根据category_id查询
      quantity: parseFloat(data.quantity),
      purchase_price: parseFloat(data.purchase_price),
      current_price: parseFloat(data.purchase_price), // 初始价格
      purchase_date: data.purchase_date,
      total_value: parseFloat(data.quantity) * parseFloat(data.purchase_price),
      profit_loss: 0,
      profit_loss_percentage: 0,
      notes: data.notes
    }
    
    return {
      code: 200,
      success: true,
      message: '添加成功',
      data: newAsset
    }
  }

  /**
   * 更新资产
   */
  async updateAsset(id: number, data: AssetFormData): Promise<ApiResponse<Asset>> {
    await delay(500)
    
    // TODO: 替换为真实API调用
    // return fetch(`/api/assets/${id}`, {
    //   method: 'PUT',
    //   headers: { 'Content-Type': 'application/json' },
    //   body: JSON.stringify(data)
    // }).then(res => res.json())
    
    const updatedAsset: Asset = {
      id,
      name: data.name,
      symbol: data.symbol,
      category_id: parseInt(data.category_id),
      category_name: '未知',
      quantity: parseFloat(data.quantity),
      purchase_price: parseFloat(data.purchase_price),
      current_price: parseFloat(data.purchase_price),
      purchase_date: data.purchase_date,
      total_value: parseFloat(data.quantity) * parseFloat(data.purchase_price),
      profit_loss: 0,
      profit_loss_percentage: 0,
      notes: data.notes
    }
    
    return {
      code: 200,
      success: true,
      message: '更新成功',
      data: updatedAsset
    }
  }

  /**
   * 删除资产
   */
  async deleteAsset(_id: number): Promise<ApiResponse<null>> {
    await delay(500)
    
    // TODO: 替换为真实API调用
    // return fetch(`/api/assets/${id}`, {
    //   method: 'DELETE'
    // }).then(res => res.json())
    
    return {
      code: 200,
      success: true,
      message: '删除成功',
      data: null
    }
  }

  /**
   * 获取资产详情
   */
  async getAsset(id: number): Promise<ApiResponse<Asset>> {
    await delay(500)
    
    // TODO: 替换为真实API调用
    // return fetch(`/api/assets/${id}`).then(res => res.json())
    
    const mockAsset: Asset = {
      id,
      name: '示例资产',
      symbol: 'EXAMPLE',
      category_id: 1,
      category_name: '股票',
      quantity: 100,
      purchase_price: 150,
      current_price: 180,
      purchase_date: '2024-01-15',
      total_value: 18000,
      profit_loss: 3000,
      profit_loss_percentage: 20
    }
    
    return {
      code: 200,
      success: true,
      message: '获取成功',
      data: mockAsset
    }
  }

  // 3. 实时价格数据

  /**
   * 获取实时价格
   */
  async getPrices(symbols: string[]): Promise<ApiResponse<Record<string, PriceData>>> {
    await delay(500)
    
    // TODO: 替换为真实API调用
    // return fetch(`/api/assets/prices?symbols=${symbols.join(',')}`).then(res => res.json())
    
    const mockPrices: Record<string, PriceData> = {}
    symbols.forEach(symbol => {
      mockPrices[symbol] = {
        symbol,
        current_price: Math.random() * 1000 + 100,
        change: Math.random() * 20 - 10,
        change_percentage: Math.random() * 10 - 5,
        last_updated: new Date().toISOString()
      }
    })
    
    return {
      code: 200,
      success: true,
      message: '获取成功',
      data: mockPrices
    }
  }

  /**
   * 获取历史价格
   */
  async getHistoryPrices(_assetId: number, _period: string): Promise<ApiResponse<HistoryPrice[]>> {
    await delay(500)
    
    // TODO: 替换为真实API调用
    // return fetch(`/api/assets/${assetId}/history?period=${period}`).then(res => res.json())
    
    const mockHistory: HistoryPrice[] = []
    for (let i = 30; i >= 0; i--) {
      const date = new Date()
      date.setDate(date.getDate() - i)
      mockHistory.push({
        date: date.toISOString().split('T')[0],
        price: Math.random() * 200 + 100,
        volume: Math.floor(Math.random() * 1000000)
      })
    }
    
    return {
      code: 200,
      success: true,
      message: '获取成功',
      data: mockHistory
    }
  }

  // 4. 投资组合统计

  /**
   * 获取投资组合概览
   */
  async getPortfolioOverview(): Promise<ApiResponse<PortfolioOverview>> {
    try {
      // 使用真实API调用，强制检查用户登录状态
      const headers = getUserAuthHeaders()
      const result = await apiRequest<ApiResponse<PortfolioOverview>>(
        API_CONFIG.ENDPOINTS.PORTFOLIO_OVERVIEW,
        { headers }
      )
      
      // 计算派生字段（暂时使用模拟数据，后续会根据实际数据调整）
      if (result.success && result.data) {
        const data = result.data
        // 计算目前的模拟值，后续需要根据实际业务逻辑调整
        data.total_profit_loss = data.total_value * 0.1 // 10%盈利模拟
        data.total_profit_loss_percentage = 10.0
        data.yesterday_change = data.total_value * 0.005 // 0.5%昨日变化模拟
        data.yesterday_change_percentage = 0.5
        data.total_asset_value = data.total_value
        data.total_cost = data.total_value * 0.9 // 90%成本模拟
      }
      
      return result
      
    } catch (error) {
      console.error('获取投资组合概览失败:', error)
      
      // 如果是未登录错误，直接抛出
      if (error instanceof Error && error.message === '用户未登录') {
        throw error
      }
      
      // 失败时返回API格式的错误响应
      return {
        code: 500,
        success: false,
        message: '获取投资组合数据失败',
        data: {
          total_value: 0,
          value: 0,
          created_at: Date.now() / 1000,
          updated_at: Date.now() / 1000,
          total_profit_loss: 0,
          total_profit_loss_percentage: 0,
          yesterday_change: 0,
          yesterday_change_percentage: 0,
          total_asset_value: 0,
          total_cost: 0
        }
      }
    }
  }

  /**
   * 获取收益趋势数据
   */
  async getRevenueTrend(days: number): Promise<ApiResponse<RevenueTrendData>> {
    try {
      const headers = getUserAuthHeaders()
      const result = await apiRequest<ApiResponse<RevenueTrendData>>(
        `${API_CONFIG.ENDPOINTS.REVENUE_TREND}?days=${days}`,
        { headers }
      )
      return result
    } catch (error) {
      console.error('获取收益趋势数据失败:', error)
      // 如果是未登录错误，直接抛出
      if (error instanceof Error && error.message === '用户未登录') {
        throw error
      }
      return {
        code: 500,
        success: false,
        message: '获取收益趋势数据失败',
        data: {
          list: [],
          total: 0,
          today: 0,
          average: '0'
        }
      }
    }
  }

  /**
   * 获取支出趋势数据
   */
  async getExpenseTrend(days: number): Promise<ApiResponse<ExpenseTrendData>> {
    try {
      const headers = getUserAuthHeaders()
      const result = await apiRequest<ApiResponse<ExpenseTrendData>>(
        `${API_CONFIG.ENDPOINTS.EXPENSE_TREND}?days=${days}`,
        { headers }
      )
      return result
    } catch (error) {
      console.error('获取支出趋势数据失败:', error)
      // 如果是未登录错误，直接抛出
      if (error instanceof Error && error.message === '用户未登录') {
        throw error
      }
      return {
        code: 500,
        success: false,
        message: '获取支出趋势数据失败',
        data: {
          list: [],
          total: 0,
          today: 0,
          average: '0'
        }
      }
    }
  }

  /**
   * 获取收益分析
   */
  async getPerformanceData(period: string): Promise<ApiResponse<PerformanceData>> {
    await delay(500)
    
    // TODO: 替换为真实API调用
    // return fetch(`/api/portfolio/performance?period=${period}`).then(res => res.json())
    
    return {
      code: 200,
      success: true,
      message: '获取成功',
      data: {
        period,
        total_return: 6.59,
        annualized_return: 8.2,
        volatility: 15.3,
        sharpe_ratio: 0.54,
        max_drawdown: -12.5
      }
    }
  }

  /**
   * 添加收益
   */
  async addRevenue(amount: number): Promise<ApiResponse<null>> {
    try {
      const url = `${API_CONFIG.BASE_URL}/assets/portfolio/revenueAdd`
      
      const requestData = {
        amount: amount
      };
      
      const headers = getUserAuthHeaders()
      const response = await fetch(url, {
        method: 'POST',
        headers: {
          ...headers,
          'Content-Type': 'application/json',
        },
        body: JSON.stringify(requestData),
      });
      
      if (!response.ok) {
        const errorText = await response.text();
        throw new Error(`HTTP error! status: ${response.status}, message: ${errorText}`);
      }

      const data = await response.json();
      return data;
    } catch (error) {
      // 如果是未登录错误，直接抛出
      if (error instanceof Error && error.message === '用户未登录') {
        throw error
      }
      return {
        code: 500,
        success: false,
        message: '添加收益失败: ' + (error instanceof Error ? error.message : String(error)),
        data: null
      };
    }
  }

  /**
   * 添加支出
   */
  async addExpense(amount: number): Promise<ApiResponse<null>> {
    try {
      const url = `${API_CONFIG.BASE_URL}/assets/expensesAdd`
      
      const requestData = {
        amount: amount
      };
      
      const headers = getUserAuthHeaders()
      const response = await fetch(url, {
        method: 'POST',
        headers: {
          ...headers,
          'Content-Type': 'application/json',
        },
        body: JSON.stringify(requestData),
      });
      
      if (!response.ok) {
        const errorText = await response.text();
        throw new Error(`HTTP error! status: ${response.status}, message: ${errorText}`);
      }

      const data = await response.json();
      return data;
    } catch (error) {
      // 如果是未登录错误，直接抛出
      if (error instanceof Error && error.message === '用户未登录') {
        throw error
      }
      return {
        code: 500,
        success: false,
        message: '添加支出失败: ' + (error instanceof Error ? error.message : String(error)),
        data: null
      };
    }
  }

  /**
   * 调整投资组合总金额
   */
  async adjustPortfolioTotalAmount(amount: number): Promise<ApiResponse<null>> {
    try {
      const url = `${API_CONFIG.BASE_URL}/assets/portfolio/updateTotalAmount`
      
      const formData = new FormData();
      formData.append('amount', amount.toString());

      const headers = getUserAuthHeaders()
      const response = await fetch(url, {
        method: 'POST',
        headers: {
          ...headers,
        },
        body: formData,
      });
      
      if (!response.ok) {
        const errorText = await response.text();
        throw new Error(`HTTP error! status: ${response.status}, message: ${errorText}`);
      }

      const data = await response.json();
      return data;
    } catch (error) {
      // 如果是未登录错误，直接抛出
      if (error instanceof Error && error.message === '用户未登录') {
        throw error
      }
      return {
        code: 500,
        success: false,
        message: '调整投资组合总金额失败: ' + (error instanceof Error ? error.message : String(error)),
        data: null
      };
    }
  }
}

// 导出单例实例
export const assetService = new AssetService()

/**
 * API接口使用说明
 * 
 * 1. 当前所有方法都是Mock实现，返回模拟数据
 * 2. 每个方法都包含TODO注释，标明需要替换的真实API调用
 * 3. 所有方法都有适当的延迟模拟真实网络请求
 * 4. 响应格式统一使用ApiResponse包装
 * 
 * 替换步骤：
 * 1. 将TODO部分的注释取消，并删除Mock实现
 * 2. 确保后端API返回的数据格式与类型定义一致
 * 3. 添加适当的错误处理和认证头
 * 4. 根据需要添加请求拦截器和响应拦截器
 */